//index.js
//获取应用实例
import api from '../../api/api.js'
import {formatProductType} from '../../utils/util'

const app = getApp();

Page({
  data: {
    profitInfo: {},
    hasUserInfo: false,
    loading: true,
    active: null,
  },
  onPullDownRefresh() {
    this.getUserProfit();
  },
  onTabItemTap() {
    wx.startPullDownRefresh()
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.init()
    } else {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.init()
      }
    }
  },
  onChange(event) {
    const {key} = event.currentTarget.dataset;
    this.setData({
      [key]: event.detail,
    });
  },
  toBuy() {
    wx.navigateTo({
      url: '/pages/transaction/select/select'
    })
  },

  toSale() {
    wx.navigateTo({
      url: '/pages/transaction/sale/sale'
    })
  },

  init() {
    this.setData({
      loading: true
    });
    this.getUserProfit();
  },

  getUserProfit() {
    api.getUserProfit().then(res => {
      let _data = res.data.data;
      _data.userProductList = _data.userProductList.map(item => {
        item.showProductType = formatProductType(item.productType);
        return item;
      });
      this.setData({
        profitInfo: _data,
        loading: false
      });
      wx.stopPullDownRefresh();
    });
  },
});